<?php


namespace App\Http\Middleware;


use App\AppContext\Admin;
use App\AppContext\Api;
use App\Utils\Encryption;
use App\Utils\Output;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

/**
 * Api内容初始化中间件
 * Class ApiContext
 * @package App\Http\Middleware
 */
class ApiContext
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //验证签名
        try {
            app()->singleton("AppContext", Api::class);
            $result = $next($request);
            return $result;
        } catch (\Throwable $e) {
            if ($e instanceof ValidationException) {
                $result = Output::fail(
                    $e->validator->errors()->first(),
                    $e->getCode() ? intval($e->getCode()) : $e->getLine(),
                    $e->validator->errors()->toArray());

            } else {
                Log::info($e->getMessage() . "\r\n" . $e->getTraceAsString());
                $result = Output::fail($e->getMessage(), -1, $e->getTrace());
            }
            return response()->json($result);
        }
    }
}
